export default class MusicCtrl {
  constructor(musicBgm, musicGame) {
    let scope = this
    // console.log('music');
    this.musicBgm = musicBgm
    this.musicGame = musicGame
    this.bgmAudioContext = document.createElement('audio')
    this.gameAudioContext = document.createElement('audio')
    //播放背景音乐
    this.playBgmAudio()
    document.addEventListener('visibilitychange', function() {
      // console.log(document.hidden)
      if (document.hidden) {
        scope.stopBgmAudio()
      } else {
        scope.continueBgmAudio()
      }
    })
  }
  //播放背景音乐(有参数进行指定播放，无参数进行默认播放)
  playBgmAudio(musicBgm) {
    if (!musicBgm) {
      musicBgm = this.musicBgm
    }
    let audio = this.bgmAudioContext
    if(!musicBgm.url){
      audio.pause()
      return
    }
    if (musicBgm) {
      audio.autoplay = true
      audio.loop = true
      audio.volume = musicBgm.volume
      audio.src = '.' + musicBgm.url
      audio.play()
    }
  }
  //继续播放
  continueBgmAudio() {
    this.bgmAudioContext.play()
  }
  //暂停播放
  stopBgmAudio() {
    this.bgmAudioContext.pause()
  }
  //播放游戏音效
  playGameAudio({ musicGame, type }) {
    
    let audio = this.gameAudioContext
    if (!musicGame) {
      musicGame = this.musicGame
    }
    if(musicGame.id==0){
      return
    }
    // console.log(musicGame.id,type);
    if (musicGame?.id != 0) {
      audio.src = '.' + musicGame[type]
      // audio.autoplay = true
      audio.play()
    }
  }
}
